/*
 * @Author: i@rysa.cn
 * @Date: 2022-04-09 21:28:45
 * @LastEditTime: 2022-04-13 15:43:23
 * @LastEditors: i@rysa.cn
 * @Description:
 * @FilePath: \go-utils\sms\tencent_sms\qcloud.go
 */
package tencent_sms

import (
	"encoding/json"

	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/errors"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/profile"
	sms "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/sms/v20210111"
)

type tencentsms struct {
	*Config
}

func NewTencentSms(cfg *Config) *tencentsms {
	return &tencentsms{cfg}
}

func (s *tencentsms) Send(phone string, params []string) (string, error) {
	credential := common.NewCredential(
		s.SecretId,
		s.SecretKey,
	)
	cpf := profile.NewClientProfile()
	// cpf.Debug = true
	client, _ := sms.NewClient(credential, "ap-guangzhou", cpf)
	request := sms.NewSendSmsRequest()
	request.SmsSdkAppId = common.StringPtr(s.SdkAppId)
	request.SignName = common.StringPtr(s.Sign)
	request.TemplateId = common.StringPtr(s.TemplateId)
	request.TemplateParamSet = common.StringPtrs(params)
	request.PhoneNumberSet = common.StringPtrs([]string{phone})
	response, err := client.SendSms(request)
	if _, ok := err.(*errors.TencentCloudSDKError); ok {
		return "", err
	}
	if err != nil {
		return "", err
	}
	b, _ := json.Marshal(response.Response)
	return string(b), nil
}
